package com.kay.utils;

import com.kay.annote.Service;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Description:
 * @Author: Kay
 * @CreateDate: 2021/7/6$ 10:42$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/7/6$ 10:42$
 */
@Service
public class ConnectionUtils {
    // 单例模式下的饿汉式
//    public ConnectionUtils() {
//    }
//    private static ConnectionUtils connectionUtils = new ConnectionUtils();
//
//    public static ConnectionUtils getInstance(){
//        return connectionUtils;
//    }

    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /**
     * 从当前线程获取连接
     * @return
     * @throws SQLException
     */
    public Connection getCurrentThreadCon() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection == null){
            // 连接为空，从连接池获取一个连接，并绑定到当前连接池
            connection = DruidUtils.getInstance().getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }
}
